<template>
  <div>
    <el-form size="small" label-width="140px" ref="form" :model="obj">
      <el-card v-for="(item, index) in obj.landDetail" :key="index" class="land" shadow="hover">
        <div class="button">
          <el-button @click="handleAdd(item)" type="warning" icon="el-icon-document-copy" circle></el-button>
          <el-button
            v-show="index !== 0"
            @click="handleDelete(index)"
            type="danger"
            icon="el-icon-delete"
            circle
          ></el-button>
        </div>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="土地编码/地宗号"
              :prop="`landDetail[${index}].landCode`"
              :rules="{ required: true, message: '请输入土地编码/地宗号', trigger: 'blur' }"
            >
              <el-input
                v-model="item.landCode"
                @input="changeLandCode($event, index)"
                placeholder="请输入土地编码/地宗号"
                clearable
              />
            </el-form-item>
            <el-form-item
              label="是否农田"
              :prop="`landDetail[${index}].basicLand`"
              :rules="{ required: true, message: '请选择是否基本农田', trigger: 'blur' }"
            >
              <el-select
                v-model="item.basicLand"
                :disabled="item.disabled"
                placeholder="请选择是否基本农田"
                clearable
                style="width: 100%"
              >
                <el-option
                  v-for="item in dict.type.agriculture_basic_land"
                  :key="item.value"
                  :value="item.value"
                  :label="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="坐标（东至）">
              <el-input v-model="item.east" :disabled="item.disabled" placeholder="请输入坐标（东至）" />
            </el-form-item>
            <el-form-item label="坐标（西至）">
              <el-input v-model="item.west" :disabled="item.disabled" placeholder="请输入坐标（西至）" />
            </el-form-item>
            <el-form-item label="承包期限" :prop="`landDetail[${index}].deadline`">
              <el-input v-model="item.deadline" placeholder="请输入承包期限" clearable />
            </el-form-item>
            <el-form-item label="权证附件">
              <y-upload
                :ref="`upload${index}`"
                accept=".jpeg,.jpg,.png,.pdf,.doc,.docx"
                :path="[item.file]"
                @onSuccess="onSuccess($event, index)"
                limit="1"
              ></y-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="所属地区"
              :prop="`landDetail[${index}].deptId`"
              :rules="{ required: true, message: '请选择所属地区', trigger: 'blur' }"
            >
              <agriculture-region :value.sync="item.deptId" :disabled="item.disabled" />
            </el-form-item>
            <el-form-item
              label="面积（亩）"
              :prop="`landDetail[${index}].area`"
              :rules="{ required: true, message: '请输入面积（亩）', trigger: 'blur' }"
            >
              <el-input v-model="item.area" :disabled="item.disabled" placeholder="请输入面积（亩）" clearable />
            </el-form-item>
            <el-form-item label="坐标（南至）">
              <el-input v-model="item.south" :disabled="item.disabled" placeholder="请输入坐标（南至）" />
            </el-form-item>
            <el-form-item label="坐标（北至）">
              <el-input v-model="item.north" :disabled="item.disabled" placeholder="请输入坐标（北至）" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="item.remark" placeholder="请输入备注" type="textarea" :rows="2" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
  </div>
</template>

<script>
import { debounce } from '@/utils/common'
import landApi from '@/api/land/land'
import AgricultureRegion from '@/components/AgricultureRegion/AgricultureRegion'

export default {
  dicts: ['agriculture_basic_land'],
  components: { AgricultureRegion },
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      obj: {
        landDetail: [
          {
            landId: '',
            landCode: '',
            area: '',
            east: '',
            south: '',
            west: '',
            north: '',
            remark: '',
            deadline: '',
            file: '',
            disabled: false,
            deptId: ''
          }
        ]
      },
      landIdList: []
    }
  },
  watch: {
    list: {
      handler(newVal, oldVal) {
        if (newVal.length > 0) {
          this.obj.landDetail = newVal
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    handleDelete(index) {
      this.obj.landDetail.splice(index, 1)
    },
    handleAdd(item) {
      this.obj.landDetail.push(JSON.parse(JSON.stringify(item)))
    },
    onSuccess(url, index) {
      this.obj.landDetail[index].file = url.router
    },
    submit() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          for (let i of this.obj.landDetail) {
            if (!i.disabled) {
              const { landId } = await landApi.addLandData({
                landCode: i.landCode,
                deptId: i.deptId,
                east: i.east,
                west: i.west,
                south: i.south,
                north: i.north,
                area: i.area,
                basicLand: i.basicLand
              })
              i.landId = landId
              this.landIdList.push({ landId: landId, remark: i.remark, deadline: i.deadline, file: i.file })
            } else this.landIdList.push({ landId: i.landId, remark: i.remark, deadline: i.deadline, file: i.file })
          }
          this.$emit('submit', this.landIdList)
        }
      })
    },
    clearValidate() {
      this.landIdList = []
      this.$refs.form.clearValidate()
    },
    changeLandCode: debounce(function (val, index) {
      // 搜索土地编码/地宗号 数据回显
      landApi.landInfo({ landCode: val }).then((res) => {
        if (res.data) {
          this.$set(this.obj.landDetail[index], 'disabled', true)
          this.$set(this.obj.landDetail[index], 'landId', res.data.landId)
          this.$set(this.obj.landDetail[index], 'deptId', res.data.deptId)
          this.$set(this.obj.landDetail[index], 'east', res.data.east)
          this.$set(this.obj.landDetail[index], 'west', res.data.west)
          this.$set(this.obj.landDetail[index], 'south', res.data.south)
          this.$set(this.obj.landDetail[index], 'north', res.data.north)
          this.$set(this.obj.landDetail[index], 'area', res.data.area)
          this.$set(this.obj.landDetail[index], 'basicLand', res.data.basicLand)
        } else {
          this.$set(this.obj.landDetail[index], 'disabled', false)
        }
      })
    }, 1000),
    getFileShow() {
      for (let i in this.obj.landDetail) {
        let val = `upload${i}`
        this.$nextTick(() => {
          this.$refs[val][0].getFileShow()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.land {
  margin-bottom: 10px;
  position: relative;

  ::v-deep .el-card__body {
    padding: 15px 20px 0 20px;
  }

  ::v-deep .el-card__header {
    border-bottom: none !important;
  }

  .button {
    position: absolute;
    right: 10px;
    bottom: 10px;
    z-index: 999;
  }
}
</style>